package com.wmm.jhdriver;

import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.common.dialog.MyDialog;
import com.common.net.mywidget.LoadingDialog;
import com.common.util.SPUtils;
import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.angmarch.views.NiceSpinner;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

public class CommonActivity extends AppCompatActivity {
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.txt_one)
    EditText txtOne;
    @BindView(R.id.txt_two)
    NiceSpinner txtTwo;
    @BindView(R.id.txt_three)
    NiceSpinner txtThree;
    @BindView(R.id.txt_four)
    EditText txtFour;
    @BindView(R.id.list)
    ListView listView;
    private List<GangPingBean> list=new ArrayList<>();//扫描到的钢瓶号列表
    private List<GangPingBean> getGPs=new ArrayList<>();//获取应该有的列表
    private List<CommonBean> commonBeans=new ArrayList<>();//根据运单号获取到的客户列表
    private CommonAdapter adapter;
    ScanReceiver receiver;
    IntentFilter filter;
    private LoadingDialog dialog;
    private boolean isSubmit=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_driver);
        ButterKnife.bind(this);
        receiver = new ScanReceiver();
        filter = new IntentFilter(ScannerService.ACTION);
        dialog = new LoadingDialog(this);
        title.setText("1".equals(getIntent().getStringExtra("type"))?"落地签":"回厂签");
        adapter=new CommonAdapter(this,list);
        listView.setAdapter(adapter);
        txtOne.requestFocus();
        txtTwo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                txtThree.setSelectedIndex(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        txtThree.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                txtTwo.setSelectedIndex(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
    @Override
    protected void onResume() {
        super.onResume();
        // 注册接收器
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onPause() {
        // 卸载接收器
        unregisterReceiver(receiver);
        super.onPause();
    }

    /**
     * 获取钢瓶列表
     * @param danhao
     */
    private void getList(String danhao){
        final RequestParams requestParams = new RequestParams();
        requestParams.put("sFaYunDanHao",danhao);
        requestParams.put("sYu",SPUtils.get(this, "YuInfo", "").toString());
        HttpUtils.post(Constant.DRIVER_SAOMA_GANGPING, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            }

            @Override
            public void onStart() {
                super.onStart();
                dialog.show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                dialog.dismiss();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject object=new JSONObject(responseString);
                    if(object.getInt("success")==0){
                        JSONArray array = object.getJSONArray("data");
                        JSONObject object1;
                        GangPingBean bean;
                        getGPs.clear();
                        for(int i=0;i<array.length();i++){
                            bean=new GangPingBean();
                            object1=array.getJSONObject(i);
                            bean.setGangPingHao(object1.getString("gangpinghao"));
                            getGPs.add(bean);
                        }
                    }else{
                        T.showShort(CommonActivity.this,object.getString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 获取客户列表
     * @param danhao
     */
    private void getCustomer(final String danhao){
        final RequestParams requestParams = new RequestParams();
        Map<String,String> map=new HashMap<>();
        map.put("sFaYunDanHao", "'"+danhao+"'");
        map.put("sYu", "'"+SPUtils.get(this, "YuInfo", "").toString()+"'");
        requestParams.put("sJson",map.toString().replace("=",":"));
        HttpUtils.post(Constant.DRIVER_LUODI_SAOMA, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            }

            @Override
            public void onStart() {
                super.onStart();
                dialog.show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                dialog.dismiss();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject object=new JSONObject(responseString);
                    if(object.getInt("success")==0){
                        JSONArray array = object.getJSONArray("data");
                        JSONObject object1;
                        CommonBean bean;
                        commonBeans.clear();
                        for(int i=0;i<array.length();i++){
                            bean=new CommonBean();
                            object1=array.getJSONObject(i);
                            bean.setTiSongHuoDH(object1.getString("ERP_DELIVERY_NO"));
                            bean.setCustomerName(object1.getString("ERP_DELIVERY_VAL").substring(StringUtils.ordinalIndexOf(object1.getString("ERP_DELIVERY_VAL"),">",1)+1,object1.getString("ERP_DELIVERY_VAL").length()));
                            bean.setYdHao(danhao);
                            commonBeans.add(bean);
                        }
                        List<String> dataset = new LinkedList<>();
                        List<String> dataset2 = new LinkedList<>();
                        for(int i=0;i<commonBeans.size();i++){
                            dataset.add(commonBeans.get(i).getTiSongHuoDH());
                            dataset2.add(commonBeans.get(i).getCustomerName());
                        }
                        txtTwo.attachDataSource(dataset);
                        txtThree.attachDataSource(dataset2);
                    }else{
                        T.showShort(CommonActivity.this,object.getString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public class ScanReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            if (bundle.getString(ScannerService.BAR_CODE).startsWith("SP")) {
                txtOne.setText(bundle.getString(ScannerService.BAR_CODE));
                if("1".equals(getIntent().getStringExtra("type"))){
                    getList(bundle.getString(ScannerService.BAR_CODE));
                }
                txtOne.requestFocus();
                getCustomer(bundle.getString(ScannerService.BAR_CODE));
            } else {
                if(commonBeans.size()<=0){
                    T.showShort(CommonActivity.this,"请先扫描运单号");
                    return;
                }
                if(txtFour.getText().toString().equals( bundle.getString(ScannerService.BAR_CODE))){
                    return;
                }
                txtFour.requestFocus();
                for(int i=0;i<list.size();i++){
                    if(list.get(i).getGangPingHao().equals(bundle.getString(ScannerService.BAR_CODE).toUpperCase())){
                        T.showShort(CommonActivity.this,"钢瓶已扫过");
                        return;
                    }
                }
                if("1".equals(getIntent().getStringExtra("type"))){
                    for(int i=0;i<getGPs.size();i++){
                        if(getGPs.get(i).getGangPingHao().equals(bundle.getString(ScannerService.BAR_CODE).toUpperCase())){
                            GangPingBean bean=new GangPingBean();
                            bean.setGangPingHao(bundle.getString(ScannerService.BAR_CODE).toUpperCase());
                            list.add(bean);
                            txtFour.setText(bundle.getString(ScannerService.BAR_CODE).toUpperCase());
                            break;
                        }
                    }
                    adapter.notifyDataSetChanged();
                }else{
                    ISOK((bundle.getString(ScannerService.BAR_CODE).toUpperCase()));
                }
            }
//            mEditText.append("barcode: "
//                    + bundle.getString(ScannerService.BAR_CODE) + "\ntype: "
//                    + bundle.getString(ScannerService.CODE_TYPE) + "\nlength: "
//                    + bundle.getInt(ScannerService.LENGTH) + "\n");
        }
    }
    /**
     * @param danhao
     */
    private void ISOK(final String danhao){
        final RequestParams requestParams = new RequestParams();
        Map<String,String> map=new HashMap<>();
        map.put("gangpinghao", "'"+danhao+"'");
        map.put("YuInfo", "'"+SPUtils.get(this, "YuInfo", "").toString()+"'");
        map.put("fayundanhao", "'"+txtOne.getText().toString().trim()+"'");
        requestParams.put("sJson",map.toString().replace("=",":"));
        HttpUtils.post(Constant.YZ, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            }

            @Override
            public void onStart() {
                super.onStart();
                dialog.show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                dialog.dismiss();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject object=new JSONObject(responseString);
                    if(object.getInt("success")==0){
                        GangPingBean bean=new GangPingBean();
                        bean.setGangPingHao(danhao);
                        list.add(bean);
                        txtFour.setText(danhao);
                        adapter.notifyDataSetChanged();
                    }else{
                        T.showShort(CommonActivity.this,object.getString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    // 将 student 对象的值存储到 ContentValues 中
    private ContentValues studentToContentValues(Bean bean) {
        ContentValues contentValues = new ContentValues();
        contentValues.put("type", bean.type);
        contentValues.put("list", bean.list);
        contentValues.put("ydhao",bean.ydhao);
        contentValues.put("kehu",bean.kehu);
        contentValues.put("time",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        return contentValues;
    }

    private void submit(){
        JSONArray array=null;
        try {
            array=new JSONArray();
            JSONObject object;
            final List<GangPingBean> list=adapter.getLists();
            for(int i=0;i<list.size();i++){
                object=new JSONObject();
                object.put("gangpinghao",list.get(i).getGangPingHao());
                array.put(object);
            }
            object=new JSONObject();
            object.put("sFaYunDanHao",txtOne.getText().toString().trim());
            object.put("sYu",SPUtils.get(this,"YuInfo","").toString());
            object.put("sYunshufangshi","1".equals(getIntent().getStringExtra("type"))?"0":"1");
            object.put("GangPingHao",array.toString().replace("=",":"));
            RequestParams requestParams=new RequestParams();
            requestParams.put("sJson",object.toString().replace("=",":"));
            HttpUtils.post(Constant.DRIVER_LUODI_SUBMIT, requestParams, new TextHttpResponseHandler() {
                @Override
                public void onStart() {
                    super.onStart();
                    dialog.show();
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    dialog.dismiss();
                }
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    MyDialog.showMaterialDialog(getSupportFragmentManager(), "提示", "网络信号不好，需要保存记录之后提交吗", "继续提交", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            submit();
                        }
                    }, "保存返回", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bean bean=new Bean();
                            bean.type=getIntent().getStringExtra("type");
                            bean.kehu=commonBeans.get(txtThree.getSelectedIndex()).getCustomerName()+""+commonBeans.get(txtThree.getSelectedIndex()).getTiSongHuoDH();
                            bean.ydhao=txtOne.getText().toString();
                            bean.list=new Gson().toJson(list);
                            ContentValues contentValues=studentToContentValues(bean);
                            MyApp.getInstance().insert(SQLiteDbHelper.TABLE_STUDENT,null,contentValues);
                            finish();
                        }
                    }).show();
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    try {
                        JSONObject object1=new JSONObject(responseString);
                        if(object1.getInt("success")==0){
                            T.showShort(CommonActivity.this,"提交成功");
                            isSubmit=true;
                            finish();
                        }else{
                            T.showShort(CommonActivity.this,object1.getString("message"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if(!isSubmit&&list.size()>0){
            MyDialog.showMaterialDialog(getSupportFragmentManager(), "提示", "数据未提交，继续退出吗？", "退出", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            }, "再想想", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                }
            }).show();
            return;
        }
        finish();
    }

    @OnClick({R.id.btn_login, R.id.btn_cancle})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                if(list.size()<=0){
                    T.showShort(this,"空数据不能提交");
                    return;
                }
                if(isSubmit){
                    T.showShort(this,"信息已提交过");
                    return;
                }
                submit();
                break;
            case R.id.btn_cancle:
                if(!isSubmit&&list.size()>0){
                    T.showShort(this,"有信息待提交");
                    return;
                }
                finish();
                break;
        }
    }
}
